﻿TEST_TITLE = 'SqlServer Connection Test';

//******** SQLSERVER FIELDSET ***********//
var fsSQLServer = new Ext.form.FieldSet({
    id: 'dbFieldset',
    border: false,
    frame: false,
    autoHeight: true,
    collapsible: true,
    defaultType: 'textfield',
    defaults: {
        width: 240
    },
    labelWidth: 110,
    items: [{
        fieldLabel: 'Server',
        name: 'sqlServer',
        allowBlank: false
    }, {
        fieldLabel: 'User',
        name: 'sqlServerUser',
        allowBlank: false
    }, {
        fieldLabel: 'Password',
        name: 'sqlServerPassword',
        allowBlank: false
    }, {
        fieldLabel: 'Database Name',
        name: 'sqlServerDbName',
        allowBlank: false
    }, {
        xtype: 'panel',
        id: 'testPanel',
        width: 500,
        layout: 'hbox',
        height: 30,
        align: 'bottom',
        bodyStyle: 'padding-left: 115px;',
        items: [{
            xtype: 'button',
            id: 'btnTest',
            cls: 'x-btn-text-icon',
            icon: '/icons/lightning.png',
            text: 'test',
            autoHeight: true,
            handler: function(){
                Ext.getCmp('failedLabel').hide();
                Ext.getCmp('succeededLabel').hide();
                Ext.getCmp('testingLabel').show();
                
                /****** RUN AJAX DELETE *******/
                Ext.Ajax.request({
                    url: 'rest/dbtest',
                    method: 'GET',
                    params: {
                        sqlServerUser: fsSQLServer.items.get("sqlServerUser"),
                        sqlServerPassword: fsSQLServer.items.get("sqlServerPassword"),
                        sqlServer: fsSQLServer.items.get("sqlServer"),
                        sqlServerDbName: fsSQLServer.items.get("sqlServerDbName")
                    },
                    success: function(result, request){
                        Ext.getCmp('testingLabel').hide();
                        Ext.getCmp('succeededLabel').show();
                        return;
                    },
                    failure: function(result, request){
                        Ext.getCmp('testingLabel').hide();
                        Ext.getCmp('failedLabel').show();
                        return;
                    }
                }); //end ajax requst
            } //end handler
        }, //end testPanel item (CARD DECK #0)
        {
            id: 'testingLabel',
            xtype: 'label',
            text: 'testing connection...',
            cls: 'loading',
            hidden: true
        }, {
            id: 'failedLabel',
            xtype: 'label',
            text: 'Test failed.',
            cls: 'failed',
            hidden: true
        }, {
            id: 'succeededLabel',
            xtype: 'label',
            text: 'Test succeeded!',
            cls: 'succeeded',
            hidden: true
        }] //end testPanel items              
    } //end panel item
] //end fsSQLServer items
});

//********* DB TYPE RADIO GROUP **********//
var rgDBTypes = new Ext.form.RadioGroup({
    required: true,
    name: 'databaseTypeID',
    id: 'optDBType',
    allowBlank: false,
    fieldLabel: 'Database Type',
    defaults: {
        border: false,
        layout: 'form',
        labelWidth: 15,
        style: {
            paddingTop: '3px',
            paddingRight: '2px'
        }
    },
    items: [{
        boxLabel: 'SQLServer',
        name: 'databaseTypeID',
        inputValue: 1,
        listeners: {
            check: function(chkbox, checked){
                if (checked == true) 
                    fsSQLServer.show();
            }
        }
    }, {
        boxLabel: 'SQLServer Compact Edition',
        name: 'databaseTypeID',
        inputValue: 2,
        listeners: {
            check: function(chkbox, checked){
                if (checked == true) 
                    fsSQLServer.hide();
            }
        }
    }, {
        boxLabel: 'XML',
        disabled: true,
        name: 'databaseTypeID',
        inputValue: 3
    }]
});


//********** MANAGED APP FORM **************
var pnlManagedApp = new Ext.ux.SissonixPanel({
    id: 'pnlManagedApp',
    title: 'Managed Application',
    labelWidth: 120,
    labelPad: 5,
    defaultType: 'textfield',
    items: [
        {
            hidden: true,
            hideMode: 'display',
            name: 'ManagedAppID'
        }, {
            width: 240,
            fieldLabel: 'App Name',
            helpText: 'This is the name that will be used to identify this application in the navigation tree on the left.',
            name: 'AppName',
            allowBlank: false
        },
        //rgDBTypes, 
        {
            xtype: 'radiogroup',
            fieldLabel: 'Database',
            name: 'rgDBTypes',
            items: [
                {boxLabel: 'SQLServer', name: 'rgDBTypes', inputValue: 1, checked: true},
                { boxLabel: 'SQLServer Compact Edition', name: 'rgDBTypes', inputValue: 2 },
                { boxLabel: 'XML', name: 'rgDBTypes', inputValue: 3 }
            ]
        },
        fsSQLServer],
    buttons: [
        {
        //************** POPUP BUTTON "SAVE" ********************
        text: 'Save',
        cls: 'x-btn-text-icon',
        icon: '/icons/accept.png',
        formBind: true,
        minWidth: 75,
        handler: function(){
            f = pnlManagedApp.getForm();
            id = f.getValues().id;
            adding = (id != '');
            f.method = (adding ? 'POST' : 'PUT');
            f.url = (adding ? '/rest/user' : '/rest/user/' + id);
            return;
            
            //TODO!!!!!
            f.submit({
                /*if the returned JSON has success: true then this will hit.
                 Otherwise, if success:false is found, the failure function will be called.*/
                success: function(f, a){
                    /*a is an "action" of type Ext.form.Action.Submit.
                     When a form is submitted the action (in this case its a "Submit" type)
                     takes care of sending to the server and processing the response.
                     The assumption is that the returned HTML is a JSON object so
                     in the return Ext.form.Action.Submit object (my "a" variable)
                     there's a "result" property that was built by taking the
                     returned HTML and using the javascript "eval" command to turn
                     that JSON into a javascript object.
                     */
                    ctxMenuRecord = window.ctxMenuRecord;
                    adding = (ctxMenuRecord == null);
                    if (adding) {
                        var rt = dsUsers.recordType;
                        var ctxMenuRecord = new rt();
                        ctxMenuRecord.loadDefaults();
                    }
                    for (var i in a.result.data) {
                        fldName = i;
                        fldValue = a.result.data[i];
                        ctxMenuRecord.set(fldName, fldValue)
                    }
                    if (adding) 
                        dsUsers.addSorted(ctxMenuRecord);
                    ctxMenuRecord.commit();
                    
                    dsUsers.commitChanges();
                    winMain.hide()
                    msg = ctxMenuRecord.data.FirstName + ' ' + (adding ? 'added' : 'updated') + '!'
                    SetStatus(msg, true);
                    dsUsers.commitChanges();
                    //Ext.Msg.alert('Database Updates', msg);
                },
                failure: function(f, a){
                    if (a.failureType === Ext.form.Action.CONNECT_FAILURE) {
                        Ext.Msg.alert('Failure', 'Server reported:' + a.response.status + ' ' + a.response.statusText);
                    }
                    if (a.failureType === Ext.form.Action.SERVER_INVALID) {
                        Ext.Msg.alert('Warning', a.result.errormsg);
                    }
                }
            }); //end f.submit
        } //end handler
    }, //end save button
    {
        //************** POPUP BUTTON "CANCEL" ********************
        text: 'Cancel',
        minWidth: 75,
        cls: 'x-btn-text-icon',
        icon: '/icons/cancel.png',
        handler: function(){
            alert('cancelled!');
        }
    }]
});


//********** DOMAIN FORM **************
var pnlDomain = {
    url: '/rest/user',
    method: 'POST',
    xtype: 'form',
    id: 'pnlDomain',
    labelWidth: 75,
    title: 'Domain',
    bodyStyle: 'padding:15px',
    labelPad: 20,
    layoutConfig: {
        labelSeparator: ''
    },
    defaults: {
        width: 230,
        msgTarget: 'side'
    },
    defaultType: 'textfield',
    items: [{
        hidden: true,
        hideMode: 'display',
        name: 'id'
    }, {
        fieldLabel: 'First Name',
        name: 'first',
        allowBlank: false
    }, {
        fieldLabel: 'Last Name',
        name: 'last'
    }, {
        fieldLabel: 'Company',
        name: 'company'
    }, {
        fieldLabel: 'Email',
        name: 'email',
        vtype: 'email'
    }],
    buttons: [{
        //************** POPUP BUTTON "SAVE" ********************
        text: 'Saver',
        cls: 'x-btn-text-icon',
        icon: '/icons/accept.png',
        formBind: true,
        minWidth: 75,
        handler: function(){
            f = pnlDomain.getForm();
            adding = (ctxMenuRecord == null);
            f.method = (adding ? 'POST' : 'PUT');
            f.url = (adding ? '/rest/user' : '/rest/user/' + ctxMenuRecord.data.UserID);
            f.submit({
                /*if the returned JSON has success: true then this will hit.
                 Otherwise, if success:false is found, the failure function will be called.*/
                success: function(f, a){
                    /*a is an "action" of type Ext.form.Action.Submit.
                     When a form is submitted the action (in this case its a "Submit" type)
                     takes care of sending to the server and processing the response.
                     The assumption is that the returned HTML is a JSON object so
                     in the return Ext.form.Action.Submit object (my "a" variable)
                     there's a "result" property that was built by taking the
                     returned HTML and using the javascript "eval" command to turn
                     that JSON into a javascript object.
                     */
                    ctxMenuRecord = window.ctxMenuRecord;
                    adding = (ctxMenuRecord == null);
                    if (adding) {
                        var rt = dsUsers.recordType;
                        var ctxMenuRecord = new rt();
                        ctxMenuRecord.loadDefaults();
                    }
                    for (var i in a.result.data) {
                        fldName = i;
                        fldValue = a.result.data[i];
                        ctxMenuRecord.set(fldName, fldValue)
                    }
                    if (adding) 
                        dsUsers.addSorted(ctxMenuRecord);
                    ctxMenuRecord.commit();
                    
                    dsUsers.commitChanges();
                    winMain.hide()
                    msg = ctxMenuRecord.data.FirstName + ' ' + (adding ? 'added' : 'updated') + '!'
                    SetStatus(msg, true);
                    dsUsers.commitChanges();
                    //Ext.Msg.alert('Database Updates', msg);
                },
                failure: function(f, a){
                    if (a.failureType === Ext.form.Action.CONNECT_FAILURE) {
                        Ext.Msg.alert('Failure', 'Server reported:' + a.response.status + ' ' + a.response.statusText);
                    }
                    if (a.failureType === Ext.form.Action.SERVER_INVALID) {
                        Ext.Msg.alert('Warning', a.result.errormsg);
                    }
                }
            });
        }
    }, {
        //************** POPUP BUTTON "CANCEL" ********************
        text: 'Cancel',
        minWidth: 75,
        cls: 'x-btn-text-icon',
        icon: '/icons/cancel.png',
        handler: function(){
            winMain.hide()
        }
    }]
};

var rootForm = {
    xtype: 'panel',
    id: 'rootForm',
    html: '<img src=\'images/RestManagerheader.gif\'><br>For help see <a href=\'extrest/codeplex.com\'>ExtREST Codeplex</a> for more details.'
};

//************* TREE CARD DECK ****************
var contentPanel = new Ext.Panel({
    id: 'content-panel',
    region: 'center',
    layout: 'card',
    margins: '2 5 5 0',
    activeItem: 0,
    border: false,
    items: [rootForm, pnlManagedApp, //from managedApp.js
 pnlDomain //from domain.js
]
});

var treeLoader = new Ext.tree.TreeLoader({
    dataUrl: 'rest/managedapp?getTree=true&appNodeCls=app-node&domainNodeCls=domain-node',
    requestMethod: 'GET'
});

var rootAppNode = new Ext.tree.AsyncTreeNode({
    id: 'main',
    text: 'Managed Applications',
    cls: 'main-node'
});


//********** APP TREE *************//
var treeApplications = new Ext.tree.TreePanel({
    title: '',
    region: 'west',
    collapsible: false,
    split: true,
    loader: treeLoader,
    root: rootAppNode,
    height: 300,
    rootVisible: false,
    width: 200,
    tbar: [{
        id: 'btnAddApp',
        tooltip: 'Add New Application',
        icon: 'icons/server_add.png',
        cls: 'x-btn-icon',
        handler: function(){
            alert('add app!');
        }
    }, '-', {
        id: 'btnDelApp',
        enabled: false, //starts false but see syncTreeButtons()
        tooltip: 'Delete Application',
        icon: 'icons/server_delete.png',
        cls: 'x-btn-icon',
        handler: function(){
            alert('del app!');
        }
    }, '-', {
        id: 'btnAddDomain',
        enabled: false, //starts false but see syncTreeButtons()
        tooltip: 'Add New Domain',
        icon: 'icons/application_osx_add.png',
        cls: 'x-btn-icon',
        handler: function(){
            alert('add domain!');
        }
    }, '-', {
        id: 'btnDelDomain',
        enabled: false, //starts false but see syncTreeButtons()
        tooltip: 'Delete Domain',
        icon: 'icons/application_osx_delete.png',
        cls: 'x-btn-icon',
        handler: function(){
            alert('add domain!');
        }
    }, '-', {
        id: 'btnExpandAppTree',
        tooltip: 'Expand all',
        icon: 'icons/expand-all.gif',
        cls: 'x-btn-icon',
        handler: function(){
            treeApplications.expandAll();
        }
    }, '-', {
        id: 'btnCollapseAppTree',
        tooltip: 'Collapse all',
        icon: 'icons/collapse-all.gif',
        cls: 'x-btn-icon',
        handler: function(){
            treeApplications.collapseAll();
        }
    }]
});


//************** TREE MENU ********************
var treeMenu = new Ext.menu.Menu({
    items: [{
        text: 'Add Sub-Domain',
        id: 'popupadd',
        icon: 'icons/application_osx_add.png',
        handler: function(){
            alert('add');
        }
    }, {
        text: 'Delete Domain',
        id: 'popupDelete',
        icon: 'icons/application_osx_delete.png',
        disabled: false,
        handler: function(){
            alert('del');
        }
    }]
});

//************** TREE CLICK ********************
treeApplications.on('click', function(node, e) {
    e.stopEvent(); // Stops the browser context menu from showing.
    syncTreeButtons();
    if (node.parentNode == null) {
        contentPanel.layout.setActiveItem('rootForm');
        return;
    }

    isApp = node.parentNode.id == 'main';
    if (isApp)
        EditApp(node);
    else
        contentPanel.layout.setActiveItem('pnlDomain');
});

//************** EDIT APP ********************
var EditApp = function(node) {
    contentPanel.layout.setActiveItem('pnlManagedApp');
    pnlManagedApp.getForm().load({
        waitMsg: 'Loading',
        url: 'rest/managedapp/' + node.id,
        method: 'GET',
        failure: function(form, action) {
            Ext.Msg.alert("Load failed", action.result.errorMessage);
        }
    });
}


//************** TREE RIGHT-CLICK ********************
treeApplications.on('contextmenu', function(node){
    treeMenu.show(node.ui.getEl());
});



//***** MANAGED APP TAB ******//
var tabApplications = {
    title: 'Applications',
    layout: 'border',
    iconCls: 'managedAppTab',
    items: [treeApplications, contentPanel]
};

var a = 5;

pnlManagedApp.on('change', function(fld, newval, oldval){
    alert(fld + ',' + newval + ',' + oldval);
});


var syncTreeButtons = function() {
    n = treeApplications.getSelectionModel().getSelectedNode();
    isApp = false;
    isDom = false;
    
    Ext.getCmp('btnAddApp').enable(); //can always add an app 

    if (isApp)
        Ext.getCmp('btnDelApp').enable()
    else
        Ext.getCmp('btnDelApp').disable();

    if (isApp && isDom)
        Ext.getCmp('btnAddDomain').enable();
    else
        Ext.getCmp('btnAddDomain').disable();

    if (isDom)
        Ext.getCmp('btnDelDomain').enable();
    else
        Ext.getCmp('btnDelDomain').disable();
}

var getAppRecord = function(id){

}

var saveAppRecord = function(){
	
}

fsSQLServer.hide();

